package com.guigu.qingcheng.controller;

import com.alibaba.fastjson.JSON;
import com.guigu.qingcheng.pojo.TbOrderItem;
import com.guigu.qingcheng.pojo.TbSku;
import com.guigu.qingcheng.pojo.vo.SpuAndSku;
import com.guigu.qingcheng.service.TbSkuService;
import com.guigu.qingcheng.utils.PageUtil;
import com.guigu.qingcheng.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
*
* @author Jiang
* @date 2020/07/27
*/
@Slf4j
@RestController
@RequestMapping("/sku")
@Api(tags = "TbSkuController")
public class TbSkuController {
    @Resource
    private TbSkuService tbSkuService;


    @ApiOperation(value = "查询未下架商品")
    @GetMapping("/findsku3")
    public R findsku3() {
        Map sumsku3 = tbSkuService.findsku3();
        return R.ok().data("sumsku3",sumsku3.get("sumsku3"));
    }

    @ApiOperation(value = "查询已下架商品")
    @GetMapping("/findsku2")
    public R findsku2() {
        Map sumsku2 = tbSkuService.findsku2();
        return R.ok().data("sumsku2",sumsku2.get("sumsku2"));
    }
    @ApiOperation(value = "查询所有商品")
    @GetMapping("/findsku")
    public R findsku() {
        Map sumsku = tbSkuService.findsku();
        return R.ok().data("sumsku",sumsku.get("sumsku"));
    }

    @ApiOperation(value = "根据id获取信息")
    @GetMapping("/detail/{id}")
    public R detail(@PathVariable("id") String id) {

        TbSku tbSku = tbSkuService.findById(id);
        return R.ok().data("tbSku",tbSku);
    }

    @ApiOperation(value = "获取信息（list不分页）")
    @GetMapping("/list")
    public R list() {
        List<TbSku>  list = tbSkuService.queryAll();
        return R.ok().data("list",list);
    }



    @ApiOperation(value = "获取信息（list分页）不带条件")
    @GetMapping("/listPages/{pageNum}/{pageSize}")
    public R listPages(@PathVariable("pageNum") Integer pageNum, @PathVariable("pageSize") Integer pageSize) {
        PageUtil<TbSku> pageUtils = tbSkuService.findListAll(pageNum, pageSize);

        return R.ok().data("pageUtils",pageUtils);
    }

    @ApiOperation(value = "获取信息（list分页）带条件")
    @PostMapping("pageQueryByAll/{pageNum}/{pageSize}")
    public R pageQueryByAll(@RequestBody TbSku tbSku, @PathVariable("pageNum") Integer pageNum, @PathVariable("pageSize") Integer pageSize){
        PageUtil<TbSku> pageUtils = tbSkuService.pageQueryByAll(pageNum, pageSize, tbSku);
        return R.ok().data("pageUtils",pageUtils);
    }

    @ApiOperation(value = "添加信息")
    @PostMapping("/add")
    public R add(@RequestBody TbSku tbSku) {

        boolean b = tbSkuService.saveTbSku(tbSku);
        if(b){
            return R.ok().message("添加成功");
        }
        return R.error().message("添加失败");
    }

    @ApiOperation(value = "修改信息")
    @PutMapping("/update")
    public R update(@RequestBody TbSku tbSku) {
        boolean b = tbSkuService.updateTbSku(tbSku);

        if(b){
            return R.ok().message("修改成功");
        }
        return R.error().message("修改失败");
    }

    @ApiOperation(value = "删除信息（主键）")
    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable("id") Integer id) {
        boolean b = tbSkuService.deleteById(id);
        if(b){
            return R.ok().message("删除成功");
        }
        return R.error().message("删除失败");
    }

    @ApiOperation(value = "根据skuId查询sku和spu连接查询")
    @GetMapping("/finkSkuAndSpuBySkuId/{id}")
    public R finkSkuAndSpuBySkuId(@PathVariable String id){
        SpuAndSku spuAndSku = tbSkuService.finkSkuAndSpuBySkuId(id);
        return R.ok().data("spuAndSku", spuAndSku);
    }

    /**
     * 初始化ES库
     * @return
     */
    @GetMapping("/initES")
    public R initES() {
        List<TbSku> all = tbSkuService.queryAll();

        try {
            //1.连接rest接口
            HttpHost http = new HttpHost("127.0.0.1", 9200, "http");
            RestClientBuilder builder = RestClient.builder(http);//rest构建器
            RestHighLevelClient restHighLevelClient = new
                    RestHighLevelClient(builder);//高级客户端对象

            //2.封装请求对象
            BulkRequest bulkRequest = new BulkRequest();
            for(TbSku sku: all) {
                IndexRequest indexRequest = new IndexRequest("sku", "doc", sku.getId());
                Map skuMap = new HashMap<>();
                skuMap.put("name",sku.getName());
                skuMap.put("brandName",sku.getBrandName());
                skuMap.put("categoryName",sku.getCategoryName());
                skuMap.put("price",sku.getPrice());
                skuMap.put("image", sku.getImage());

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date createTime = sku.getCreateTime();
                if(createTime!=null)
                    skuMap.put("createTime", sdf.format(sku.getCreateTime()));
                else
                    skuMap.put("createTime", null);
                skuMap.put("saleNum", sku.getSaleNum());
                skuMap.put("commentNum", sku.getCommentNum());

                Map<String, String> spec = JSON.parseObject(sku.getSpec(), Map.class);
                skuMap.put("spec",spec);
                indexRequest.source(skuMap);
                bulkRequest.add(indexRequest);
            }


            //3.获取响应结果
//        IndexResponse response = restHighLevelClient.index(indexRequest,
//        RequestOptions.DEFAULT);
            BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            int status = bulkResponse.status().getStatus();
            System.out.println(status);
            restHighLevelClient.close();

        }catch (Exception ex) {
            ex.printStackTrace();
        }

        return R.ok();
    }

    @ApiOperation(value = "查询销量最高的四件商品")
    @GetMapping("/findSkuBySaleNum")
    public R findSkuBySaleNum() {
        List<TbSku> skuBySaleNum = tbSkuService.findSkuBySaleNum();
        return R.ok().data("skuBySaleNum", skuBySaleNum);
    }


    @ApiOperation(value = "扣减库存")
    @PostMapping("/deductionStock")
    public boolean deductionStock(@RequestBody List<TbOrderItem> list){
        boolean b = this.tbSkuService.deductionStock(list);
        return b;
    }

    @ApiOperation(value = "添加库存")
    @PostMapping("/deductionStock2")
    public boolean deductionStock2(@RequestBody List<TbOrderItem> list){
        boolean b = this.tbSkuService.deductionStock2(list);
        return b;
    }
}
